﻿using Ls.Core;
using Ls.Data;
using Ls.Utils;
using Ls.Web.Framework.Permissions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Ls.Web.Admin.Areas.Sys.Models
{
    public class BackgroundJobService: BaseService
    {
        public BackgroundJobService() : base("LYJobs", "j_BackgroundJob", "后台作业",new SqlServerProvider())
        {

        }

        public BackgroundJob GetJob(Guid Id)
        {
            BackgroundJob job = db.Select<BackgroundJob>("*").From(_tblName).Where(" Id = @jobId").Parameter("jobId", Id, Ls.Data.DataTypes.Guid).QuerySingle();
            if (job == null)
            {
                return null;
            }
            List<JobTrigger> triggers = db.Select<JobTrigger>("*").From("j_Trigger").Where(" JobId = @jobId").Parameter("jobId", Id, Ls.Data.DataTypes.Guid).QueryMany();
            job.trigger = triggers;
            return job;
        }
        /// <summary>
        /// 添加作业
        /// </summary>
        /// <returns></returns>
        public int AddJob(BackgroundJob job)
        {
            int result = this.Insert(new
            {
                Id = job.Id,
                JobType = job.JobType,
                Name = job.Name,
                Status = 0,
                Description = job.Description,
                Parameters = job.Parameters,
                CreateTime = DateTime.Now,
                CreateBy = AuthHelper.GetUserRealname(),
                ModifyTime = DateTime.Now,
                ModifyBy = AuthHelper.GetUserRealname()
            });
            if (result > 0)
            {
                // 插入触发器
                if (job.trigger != null && job.trigger.Count > 0)
                {
                    foreach (var trigger in job.trigger)
                    {
                        this.Insert("j_Trigger", new
                        {
                            Id = Guid.NewGuid(),
                            JobId = job.Id,
                            Name = trigger.Name,
                            Status = 1,// trigger.Status,
                            CronExpression = trigger.CronExpression,
                            Description = CommonHelper.CronToChinese(trigger.CronExpression),
                            CreateTime = DateTime.Now,
                            CreateBy = AuthHelper.GetUserRealname(),
                            ModifyTime = DateTime.Now,
                            ModifyBy = AuthHelper.GetUserRealname()
                        });
                    }
                }

            }
            return result;
        }


        public int UpdateJob(BackgroundJob job)
        {
            int result = this.Update(new
            {
                JobType = job.JobType,
                Name = job.Name,
                Parameters = job.Parameters,
                Description = job.Description,
                Status = job.Status,
                ModifyTime = DateTime.Now,
                ModifyBy = AuthHelper.GetUserRealname()
            }, new { Id = job.Id });
            if (result > 0)
            {
                // 插入触发器
                if (job.trigger != null && job.trigger.Count > 0)
                {
                    var ids = job.trigger.Where(t => t.Id.HasValue).Select(t => t.Id.ToString()).ToList();
                    if (ids != null && ids.Count > 0)
                    {
                        this.DeleteBySql(" delete from j_Trigger where JobId=@JobId and Id not in('" + string.Join("','", ids) + "')"
                          , new { JobId = job.Id });
                    }

                    foreach (var trigger in job.trigger)
                    {
                        // 插入
                        if (trigger.Id == null || trigger.Id == Guid.Empty)
                        {
                            this.Insert("j_Trigger", new
                            {
                                Id = Guid.NewGuid(),
                                JobId = job.Id,
                                Name = trigger.Name,
                                Status = 1,//trigger.Status,
                                CronExpression = trigger.CronExpression,
                                Description = CommonHelper.CronToChinese(trigger.CronExpression),
                                CreateTime = DateTime.Now,
                                CreateBy = AuthHelper.GetUserRealname(),
                                ModifyTime = DateTime.Now,
                                ModifyBy = AuthHelper.GetUserRealname()
                            });
                        }
                        // 更新
                        else
                        {
                            this.Update("j_Trigger", new
                            {
                                Name = trigger.Name,
                                Status = 1,//trigger.Status,
                                CronExpression = trigger.CronExpression,
                                Description = CommonHelper.CronToChinese(trigger.CronExpression),
                                ModifyTime = DateTime.Now,
                                ModifyBy = AuthHelper.GetUserRealname()
                            }, new { Id = trigger.Id });
                        }
                    }
                }
                else
                {
                    this.DeleteBySql(" delete from j_Trigger where JobId=@JobId ", new { JobId = job.Id });
                }
            }
            return result;
        }
        public int UpdateTriggerState(Guid triggerId, int status)
        {
            string sql = " Update j_Trigger set Status =@status  where Id=@triggerId ";
            // 修改状态
            return Update(sql, new { triggerId = triggerId, status = status });
        }
        public int UpdateState(Guid jobId, int status)
        {
            string sql = " Update j_BackgroundJob set Status =@status  where Id=@JobId ";
            // 修改状态
            return Update(sql, new { JobId = jobId, status = status });
        }

        /// <summary>
        /// 获取所有的作业
        /// </summary>
        /// <returns></returns>
        public List<BackgroundJob> GetAllJobs()
        {
            List<BackgroundJob> jobs = db.Select<BackgroundJob>("*").From(_tblName).QueryMany();

            List<JobTrigger> triggers = db.Select<JobTrigger>("*").From("j_Trigger").QueryMany();
            foreach (BackgroundJob job in jobs)
            {
                job.trigger = triggers.Where(t => t.JobId == job.Id).ToList();
            }
            return jobs;
        }
        /// <summary>
        /// 作业执行日志
        /// </summary>
        /// <returns></returns>
        public void UpdateStateAndAddJobExcuteLog(Guid jobId, string jobName, DateTime? NextFireTimeUtc, DateTime? FireTimeUtc, DateTime? PreviousFireTimeUtc,
            long? JobRunTime, string logContent, int status, int ExcuteStaus, string ExceptionMessage)
        {
            Update(new
            {
                NextFireTimeUtc = NextFireTimeUtc,
                FireTimeUtc = FireTimeUtc,
                PreviousFireTimeUtc = PreviousFireTimeUtc,
                JobRunTime = JobRunTime,
                Status = status
            }, new { Id = jobId });

            AddJobExcuteLog(jobId, jobName,
                NextFireTimeUtc, FireTimeUtc, PreviousFireTimeUtc, JobRunTime, logContent, ExcuteStaus, ExceptionMessage);
        }

        /// <summary>
        /// 作业执行日志
        /// </summary>
        /// <returns></returns>
        public int AddJobExcuteLog(Guid jobId, string jobName, DateTime? NextFireTimeUtc, DateTime? FireTimeUtc, DateTime? PreviousFireTimeUtc,
            long? JobRunTime, string logContent, int ExcuteStaus, string ExceptionMessage)
        {
            return Insert("j_BackgroundJobLog", new
            {
                JobId = jobId,
                JobName = jobName,
                NextFireTimeUtc = NextFireTimeUtc,
                FireTimeUtc = FireTimeUtc,
                PreviousFireTimeUtc = PreviousFireTimeUtc,
                JobRunTime = JobRunTime,
                Content = logContent,
                CreateTime = DateTime.Now,
                Status = ExcuteStaus,
                ExceptionMessage = ExceptionMessage
            });
        }
    }

    public class JobActionService : BaseService
    { 
        public JobActionService() : base("LYJobs", "j_Action", "作业动作", new SqlServerProvider())
        {

        }

        public void AddAction(Guid  jobid, string Action) {

            Insert(new { JobId = jobid, Action = Action, JobState = 0, ActionResult = "", CreateTime = DateTime.Now });
        }
    }
        public class BackgroundJob
    {
        public Guid? Id { get; set; }
        public string Name { get; set; }
        public string Parameters { get; set; }
        /// <summary>
        /// 调用的类库
        /// </summary>
        public string JobType { get; set; }
        /// <summary>
        /// 状态 0 不可用 1 可用  2 任务运行中 3 任务运行结束  4 暂停中 5 暂停 
        /// </summary>
        public int Status { get; set; }

        public string Description { get; set; }
        /// <summary>
        ///动作：添加、更新、删除、运行一次、暂停
        /// </summary>
        public string Action { get; set; }
        //public DateTime CreateTime { get; set; }
        //public string CreateBy { get; set; }
        //public DateTime ModifyTime { get; set; }
        //public string ModifyBy { get; set; }

        public List<JobTrigger> trigger { get; set; }
    }
    public class JobTrigger
    {
        public JobTrigger()
        {
            Status = 1;
        }
        public Guid? Id { get; set; }
        public Guid? JobId { get; set; }
        public string Name { get; set; }
        public string CronExpression { get; set; }
        public string Description { get; set; }

        /// <summary>
        /// 状态 0 不可用 ，1 可用
        /// </summary>
        public int Status { get; set; }

        /// <summary>
        /// 状态 inserted 0 ,deleted 2 ,updated 1
        /// </summary>
        public int _status { get; set; }
        //public DateTime CreateTime { get; set; }
        //public string CreateBy { get; set; }
        //public DateTime ModifyTime { get; set; }
        //public string ModifyBy { get; set; }
    }
}
